package cc.whcode.service;

import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Vector;
import java.util.stream.Collectors;

/**
 * Copyright(C),2019-2022,云创软研工作室
 * 电子画板
 * webrtc-server - Whiteborad
 *
 * @author : MaxLij
 * @since : 2022-08-29 16:36
 */
@ServerEndpoint("/whiteboard/{roomId}")
@Component
public class Whiteborad {
    private Session session;
    private String roomId;

    public static Vector<Whiteborad> clients = new Vector<>();

    @OnOpen
    public void onOpen(Session session, @PathParam("roomId") String roomId) {
        this.session = session;
        this.roomId = roomId;
        clients.add(this);
        System.out.println("新连接链接");
    }

    @OnClose
    public void onClose(Session session) {
        clients.remove(this);
        System.out.println("失去一个连接");
    }

    @OnMessage(maxMessageSize = 5242800)
    public void onMessage(String message, Session session) {
        JSONObject jsonObject = JSONObject.parseObject(message);
        for (Whiteborad client : clients.stream().filter(item -> item.roomId.equals(jsonObject.get("roomId"))).collect(Collectors.toList())) {
            try {
                client.session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}